package com.ywwxhz.app;

import android.app.ActionBar;
import android.app.ActivityManager;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.provider.Settings;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;

import com.ywwxhz.Util.FileKit;
import com.ywwxhz.Util.PreferencesKit;
import com.ywwxhz.Util.ToolKit;
import com.ywwxhz.Util.UIKit;
import com.ywwxhz.adapter.ProcessListAdapter;
import com.ywwxhz.lib.SwipeDismissListViewTouchListener;
import com.ywwxhz.lib.SystemBarTintManager;
import com.ywwxhz.model.AppInfo;
import com.ywwxhz.taskmgr.R;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class TaskListActivity extends ListActivity implements
        OnItemLongClickListener {
    private ActivityManager am = null;
    private PackageManager pm = null;
    private ActionBar actionBar = null;
    private ListView listview;
    private ProgressDialog myDialog;
    private ProcessListAdapter browseAppAdapter = null;
    private int delay = 5000;
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        public void run() {
            getlist();
        }
    };
    Runnable notifylist = new Runnable() {
        public void run() {
            browseAppAdapter.notifyDataSetChanged();
            actionBar.setSubtitle("可用内存"
                    + ToolKit.getAvaliableMemory(getApplicationContext(), am));
            myDialog.dismiss();
            handler.postDelayed(runnable, delay);
        }
    };
    private ActionMode actionMode;
    private int padding;
    private SystemBarTintManager systemBarTintManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        UIKit.setBackIcon(getActionBar(), getResources().getDrawable(R.drawable.ic_menu_back));
        myDialog = ProgressDialog.show(this, null, getString(R.string.Loading),
                true, true);
        browseAppAdapter = new ProcessListAdapter(this);
        pm = this.getPackageManager();
        am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        listview = getListView();
        listview.setFastScrollEnabled(true);
        listview.setDivider(null);
        padding = ToolKit.dip2px(this, 5);
        listview.setPadding(padding, padding, padding, padding);
        systemBarTintManager = UIKit.buildTranslucentStatus(this, listview, getResources().getColor(R.color.task_statusbar_bg));
        actionBar = getActionBar();
        SwipeDismissListViewTouchListener touchListener = new SwipeDismissListViewTouchListener(
                listview,
                new SwipeDismissListViewTouchListener.DismissCallbacks() {
                    @Override
                    public boolean canDismiss(int position) {
                        return true;
                    }

                    @Override
                    public void onDismiss(ListView listView,
                                          int[] reverseSortedPositions) {
                        for (int position : reverseSortedPositions) {
                            ToolKit.Kill_Proc(
                                    browseAppAdapter.getDataSet().get(position)
                                            .getPkgName(), am);
                            browseAppAdapter.getDataSet().remove(position);
                        }
                        browseAppAdapter.notifyDataSetChanged();
                        getlist();
                    }
                });
        listview.setOnTouchListener(touchListener);
        listview.setOnScrollListener(touchListener.makeScrollListener());
        listview.setOnItemLongClickListener(this);
        listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                if (actionMode != null) {
                    actionMode.finish();
                }
            }
        });
        listview.setAdapter(browseAppAdapter);
        handler.post(runnable);
    }

    private synchronized List<AppInfo> getRunningAppInfo()
            throws NullPointerException {
        boolean showignore = PreferencesKit.getboolean(this, "showIgnore", false);
        String ignorelist = ToolKit.getIgnoreList(this);
        List<ActivityManager.RunningAppProcessInfo> appProcessList = am
                .getRunningAppProcesses();
        List<AppInfo> queryrunningApps = new ArrayList<AppInfo>();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcessList) {
            String processName = appProcess.processName;
            String[] pkgNameList = appProcess.pkgList;
            boolean isignore = ignorelist.contains(pkgNameList[0])
                    || ignorelist.contains(processName);
            if (showignore || !isignore) {
                ApplicationInfo appInfo;
                int pid = appProcess.pid; // pid
                int[] myMempid = new int[]{pid};
                Debug.MemoryInfo[] memoryInfo = am
                        .getProcessMemoryInfo(myMempid);
                long memSize = memoryInfo[0].getTotalPss() * 1024;
                String size = FileKit.formateFileSize(this, memSize);
                for (String aPkgNameList : pkgNameList) {
                    try {
                        int type;
                        appInfo = pm.getApplicationInfo(aPkgNameList,
                                PackageManager.GET_UNINSTALLED_PACKAGES);
                        if (!isignore) {
                            if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                                type = 0;
                            } else {
                                type = 1;
                            }
                        } else {
                            type = 2;
                        }
                        queryrunningApps.add(getAppInfo(appInfo, processName,
                                size, type));
                    } catch (NameNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        Collections.sort(queryrunningApps, new Comparator<AppInfo>() {

            @Override
            public int compare(AppInfo lhs, AppInfo rhs) {
                return lhs.getFlag() - rhs.getFlag();
            }
        });
        return queryrunningApps;
    }

    private void getlist() {
        handler.removeCallbacks(runnable);
        new Thread() {
            public void run() {
                try {
                    browseAppAdapter.setDataSet(getRunningAppInfo());
                    handler.post(notifylist);
                } catch (NullPointerException ignored) {

                }
            }
        }.start();
    }

    private AppInfo getAppInfo(ApplicationInfo app, String processName,
                               String memsize, int type) {
        AppInfo appInfo = new AppInfo();
        appInfo.setAppLabel((String) app.loadLabel(pm));
        appInfo.setAppIcon(app.loadIcon(pm));
        appInfo.setPkgName(app.packageName);
        appInfo.setProcessName(processName);
        appInfo.setMemSize(memsize);
        appInfo.setFlag(type);
        return appInfo;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_tasklist, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        switch (item.getItemId()) {
            case R.id.killall:
                for (AppInfo proc : browseAppAdapter.getDataSet()) {
                    ToolKit.Kill_Proc(proc.getPkgName(), am);
                }
                ToolKit.MakeToast(this,
                        "清理完成，可用内存 " + ToolKit.getAvaliableMemory(this, am));
                getlist();

                break;
            case R.id.refresh:
                myDialog.show();
                getlist();
                break;
            case R.id.settings:
                intent.setClass(this, SettingsActivity.class);
                startActivityForResult(intent, 0);
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.runFinalization();
        System.gc();
        System.exit(0);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view,
                                   int position, long id) {
        handler.removeCallbacks(runnable);
        actionMode = startActionMode(new TaskMode(view, position));
        return true;
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case RESULT_OK:
                handler.post(runnable);
                break;
            default:
                break;
        }
    }

    private class TaskMode implements ActionMode.Callback {
        private int pos;
        private int type;
        private View view;

        public TaskMode(View view, int pos) {
            this.pos = pos;
            this.view = view;
            type = browseAppAdapter.getDataSet().get(pos).getFlag();
        }

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            view.setActivated(true);
            mode.setTitle(browseAppAdapter.getDataSet().get(pos).getAppLabel());
            mode.setSubtitle(browseAppAdapter.getDataSet().get(pos)
                    .getPkgName());
            if (type != 2) {
                menu.add(0, 0, 0, "添加到忽略列表").setIcon(android.R.drawable.ic_menu_add);
            }
            menu.add(0, 1, 0, "强行停止").setIcon(R.drawable.ic_menu_stop);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
                case 0:
                    ToolKit.addToIgnoreList(getApplicationContext(), browseAppAdapter
                            .getDataSet().get(pos).getPkgName());
                    getlist();
                    break;

                case 1:
                    Intent intent = new Intent(
                            Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", browseAppAdapter
                            .getDataSet().get(pos).getPkgName(), null);
                    intent.setData(uri);
                    startActivity(intent);
                    break;
            }
            mode.finish();
            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            view.setActivated(false);
            handler.postDelayed(runnable, delay);
        }

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        UIKit.fixTranslucentStatusPadding(systemBarTintManager, listview, UIKit.PaddingMode.ALL_SAME, padding);
    }
}
